const db = require('../db');
const fs = require('fs');
const path = require('path');

const migrationsDir = path.join(__dirname, './');

// 按文件名排序执行迁移
const runMigrations = async () => {
    const files = fs.readdirSync(migrationsDir)
        .filter(file => file.endsWith('.sql'))
        .sort();

    for (const file of files) {
        const sql = fs.readFileSync(path.join(migrationsDir, file), 'utf8');
        console.log(`Running migration: ${file}`);

        await new Promise((resolve, reject) => {
            db.exec(sql, (err) => {
                if (err) reject(err);
                else resolve();
            });
        });
    }
};

// 执行并处理错误
runMigrations()
    .then(() => {
        console.log('All migrations completed successfully');
        process.exit(0);
    })
    .catch((err) => {
        console.error('Migration failed:', err);
        process.exit(1);
    });
